# coding=UTF-8
'''
Created on Jan 17, 2010

@author: Paul Lu
@author: Adolfo García
'''

from application_context import SMSAppStoreConfig
from sms_gateway import Message
from springpython.context import ApplicationContext
import logging
#import sys

_LOGGER = logging.getLogger("mx.org.came.start")

class LoggingSMSListener :
    """SMSListener that prints the received messages to the log at an 
    info level.
    """
    def __init__(self):
        pass    
    
    def message_received(self, message, notifier):
        """Logs the message data at INFO level."""
        _LOGGER.info("Listener notified. Message received: " + \
         str(message.data))

class SMSAppStoreListener :
    """SMSListener that processes SMS messages using SMSAppStore's protocol
    stack.
    """
    
    def __init__(self, appstore_dispatcher):
        """Creates a new instance of SMSAppStoreListener that enqueues messages
        to the specified SMSAppStoreDispatcher
        """
        self._appstore_dispatcher = appstore_dispatcher

    def _process_text_message(self, message, notifier, Message):
        """Replies to the message using the notifier (an instance of SMSGateway)
        """
        _LOGGER.debug("Processing text message.")
        reply = Message()
        reply.data[Message.ORIGINAL_BINARY_MESSAGE] = "I received: " + \
             message.data[Message.ORIGINAL_BINARY_MESSAGE]
        reply.data[Message.RECEIVER_PHONE_NUMBER] = \
             message.data[Message.SENDER_PHONE_NUMBER]
        notifier.send_message(reply)

    def message_received(self, message, notifier):
        """Method invoked by instances of SMSGateway to notify listeners about
        the arrival of an SMS message. If the message received contains text
        (the UDH is ''), a simple reply is sent back. Otherwise, SMSAppStore
        handles the request.
        """
        _LOGGER.debug("Message received. Processing message.")
        if message.data[Message.UDH] == "": # UDH for a text message
            self._process_text_message(message, notifier, Message)
        else:
            _LOGGER.debug("Processing binary message.")
            _LOGGER.debug("Queuing message")
            self._appstore_dispatcher.message_queue.put(message)

if __name__ == '__main__' :
    # Initialize application context
    CTX = ApplicationContext(SMSAppStoreConfig())
    _LOGGER.info("Starting SMSAppStore...")
    SMS_GATEWAY = CTX.get_object("sms_gateway")
    APPSTORE_DISPATCHER = CTX.get_object("smsappstore_dispatcher")
    SMS_GATEWAY.add_sms_listener(LoggingSMSListener())
    SMS_GATEWAY.add_sms_listener(SMSAppStoreListener(APPSTORE_DISPATCHER))
    APPSTORE_DISPATCHER.start()
    SMS_GATEWAY.start_service()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        _LOGGER.info("Keyboard Interrupt -Closing Server")
        SMS_GATEWAY.stop_service()
        APPSTORE_DISPATCHER.shutdown()
#        appStore.exit(0)
#        sys.exit(0)
